package com.pet.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.pet.system.constant.ResourceStatus;
import com.pet.system.domain.entity.SysResource;
import com.pet.system.domain.entity.SysRole;
import com.pet.system.mapper.SysRoleUserMapper;
import com.pet.system.mapper.SysUserMapper;
import com.pet.system.service.IPermissionService;
import com.pet.system.service.ISysResourceService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

/**
 * 权限服务实现类
 *
 * @author Centaurea
 */
@Service
@AllArgsConstructor
public class PermissionServiceImpl implements IPermissionService {
  private final SysUserMapper userMapper;
  private final ISysResourceService resourceService;
  private final SysRoleUserMapper roleUserMapper;

  @Override
  public Set<String> getPermissions(Integer userId) {
    Set<String> perms = new HashSet<>();
    List<String> list = userMapper.queryAllPerms(userId);
    for (String perm : list) {
      if (StringUtils.isEmpty(perm)) {
        continue;
      }
      perms.addAll(Arrays.asList(perm.trim().split(",")));
    }
    return perms;
  }

  @Override
  public List<SysRole> getRoles(Serializable userId) {
    return roleUserMapper.getRoles(userId);
  }

  @Override
  public JSONArray getMenus(Integer userId) {
    Map<String, Object> params = new HashMap<>();
    params.put("type", 1);
    params.put("status", ResourceStatus.NORMAL.getStatus());
    params.put("userId", userId);
    return resourceService.queryTree(params);
  }

  @Override
  public List<SysResource> queryResource(Integer userId) {
    Map<String, Object> params = new HashMap<>();
    params.put("type", 1);
    params.put("status", ResourceStatus.NORMAL.getStatus());
    params.put("userId", userId);
    return resourceService.queryList(params);
  }
}
